package com.ruoyi.common.utils.qugongbao;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.utils.rest.RestTemplateUtil;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author luobo
 * @title: QugongbaoUtils
 * @projectName pos
 * @description: 趣工宝第三方支付相关工具类
 * @date 2021-12-07 10:44:35
 */
@Component
public class QugongbaoUtils {
    private static final Logger log = LoggerFactory.getLogger(QugongbaoUtils.class);

    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    private Environment env;

    //趣工宝注册接口
    public JSONObject memberRegUrl(String userName, String userPhone, String idCardNo, String accountType, String bankCardNo) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();
        List<MemberRegReq.MemberRegDetail> dataList = new ArrayList<>();
        MemberRegReq.MemberRegDetail detail = MemberRegReq.MemberRegDetail.builder()
                .memberName(userName)
                .mobile(userPhone)
                .idCardNo(idCardNo)
                .accountType(accountType)
                .bankCardNo(bankCardNo)
                .build();
        dataList.add(detail);
        MemberRegReq req = MemberRegReq.builder()
                .spCode(env.getProperty("qugongbao.spCode"))
                .dataList(dataList)
                .build();
        ApiBaseRequestBean request = ApiBaseRequestBean.builder()
                .custNo(env.getProperty("qugongbao.custNo"))
                .timestamp(DatePattern.NORM_DATETIME_FORMAT.format(new Date()))
                .reqNo(IdUtils.simpleUUID())
                .body(JSONObject.toJSONString(req))
                .build();
        String signValue = Signer.sign(request, env.getProperty("qugongbao.privateKey"));
        request.setSignValue(signValue);
        String url = env.getProperty("qugongbao.host") + env.getProperty("qugongbao.memberRegUrl"); //注册
        log.info("request url=" + url);
        log.info("request data=" + JSON.toJSONString(request));
        ResponseEntity<String> temp = restTemplateUtil.post(url, request, String.class);
        if (temp.getStatusCode().value() == HttpStatus.OK.value()) {
            JSONObject jo = JSONObject.parseObject(temp.getBody());
            return jo;
        } else {
            throw new RuntimeException("趣工宝注册申请失败");
        }
    }

    //趣工宝签约接口
    public JSONObject signContract(String memberNo, String serverCallbackUrl, String pageCallbackUrl) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();
        SignContractReq req = SignContractReq.builder()
                .memberNo(memberNo)
                .spCode(env.getProperty("qugongbao.spCode"))
                .serverCallbackUrl(serverCallbackUrl)
                .pageCallbackUrl(pageCallbackUrl)
                .build();
        ApiBaseRequestBean request = ApiBaseRequestBean.builder()
                .custNo(env.getProperty("qugongbao.custNo"))
                .timestamp(DatePattern.NORM_DATETIME_FORMAT.format(new Date()))
                .reqNo(IdUtils.simpleUUID())
                .body(JSONObject.toJSONString(req))
                .build();
        String signValue = Signer.sign(request, env.getProperty("qugongbao.privateKey"));
        request.setSignValue(signValue);
        String url = env.getProperty("qugongbao.host") + env.getProperty("qugongbao.signContract"); //签约
        log.info("request url=" + url);
        log.info("request data=" + JSON.toJSONString(request));
        ResponseEntity<String> temp = restTemplateUtil.post(url, request, String.class);
        if (temp.getStatusCode().value() == HttpStatus.OK.value()) {
            JSONObject jo = JSONObject.parseObject(temp.getBody());
            return jo;
        } else {
            throw new RuntimeException("趣工宝签约申请失败");
        }
    }

    //变更银行卡
    public boolean updateBankCard(String memberNo, String bankCardNo) throws Exception {
        UpdateBankCardReq req = UpdateBankCardReq.builder()
                .memberNo(memberNo)
                .accountType("BANK")
                .bankCardNo(bankCardNo)
                .build();
        ApiBaseRequestBean request = ApiBaseRequestBean.builder()
                .custNo(env.getProperty("qugongbao.custNo"))
                .timestamp(DatePattern.NORM_DATETIME_FORMAT.format(new Date()))
                .reqNo(IdUtils.simpleUUID())
                .body(JSONObject.toJSONString(req))
                .build();
        String signValue = Signer.sign(request, env.getProperty("qugongbao.privateKey"));
        request.setSignValue(signValue);
        String url = env.getProperty("qugongbao.host") + env.getProperty("qugongbao.updateBankCard"); //变更银行卡
        log.info("request url=" + url);
        log.info("request data=" + JSON.toJSONString(request));
        ResponseEntity<String> temp = restTemplateUtil.post(url, request, String.class);
        if (temp.getStatusCode().value() == HttpStatus.OK.value()) { //变更成功
            //JSONObject jo = JSONObject.parseObject(temp.getBody());
            return true;
        } else {
            //throw new RuntimeException("趣工宝变更银行卡失败");
            return false;
        }
    }

    //变更银行卡
    public JSONObject getMemberInfo(String memberNo) throws Exception {
        UpdateBankCardReq req = UpdateBankCardReq.builder()
                .memberNo(memberNo)
                .build();
        ApiBaseRequestBean request = ApiBaseRequestBean.builder()
                .custNo(env.getProperty("qugongbao.custNo"))
                .timestamp(DatePattern.NORM_DATETIME_FORMAT.format(new Date()))
                .reqNo(IdUtils.simpleUUID())
                .body(JSONObject.toJSONString(req))
                .build();
        String signValue = Signer.sign(request, env.getProperty("qugongbao.privateKey"));
        request.setSignValue(signValue);
        String url = env.getProperty("qugongbao.host") + env.getProperty("qugongbao.getMemberInfo"); //变更银行卡
        log.info("request url=" + url);
        log.info("request data=" + JSON.toJSONString(request));
        ResponseEntity<String> temp = restTemplateUtil.post(url, request, String.class);
        if (temp.getStatusCode().value() == HttpStatus.OK.value()) { //变更成功
            JSONObject jo = JSONObject.parseObject(temp.getBody());
            return jo;
        } else {
            throw new RuntimeException("趣工宝变更银行卡失败");
        }
    }

    //趣工宝签约状态查询接口
    public JSONObject queryContractStatus(String memberNo, String contractNo) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();
        SignContractStatusReq req = SignContractStatusReq.builder()
                .memberNo(memberNo)
                .spCode(env.getProperty("qugongbao.spCode"))
                //.contractNo(contractNo)
                .build();
        ApiBaseRequestBean request = ApiBaseRequestBean.builder()
                .custNo(env.getProperty("qugongbao.custNo"))
                .timestamp(DatePattern.NORM_DATETIME_FORMAT.format(new Date()))
                .reqNo(IdUtils.simpleUUID())
                .body(JSONObject.toJSONString(req))
                .build();
        String signValue = Signer.sign(request, env.getProperty("qugongbao.privateKey"));
        request.setSignValue(signValue);
        String url = env.getProperty("qugongbao.host") + env.getProperty("qugongbao.queryContractStatus"); //签约
        log.info("request url=" + url);
        log.info("request data=" + JSON.toJSONString(request));
        ResponseEntity<String> temp = restTemplateUtil.post(url, request, String.class);
        if (temp.getStatusCode().value() == HttpStatus.OK.value()) {
            JSONObject jo = JSONObject.parseObject(temp.getBody());
            return jo;
        } else {
            throw new RuntimeException("趣工宝签约状态查询失败");
        }
    }

    //趣工宝提现接口
    public Map<String, String> withdrawalForPay(String custTransId, String custOrderNo, String memberNo, BigDecimal transAmount) throws Exception {
        Map<String, String> resultMap = new HashMap<String, String>();
        List<WithdrawalReq.WithdrawalDetail> dataList = new ArrayList<>();
        WithdrawalReq.WithdrawalDetail detail = WithdrawalReq.WithdrawalDetail.builder()
                .custTransId(custTransId)
                .memberNo(memberNo)
                .amount(transAmount.longValue())
                .build();
        dataList.add(detail);
        WithdrawalReq req = WithdrawalReq.builder()
                .custOrderNo(custOrderNo)
                .spProdCode(env.getProperty("qugongbao.spProdCode"))
                .notifyUrl(env.getProperty("qugongbao.withdrawalResultNotify"))
                .dataList(dataList)
                .build();
        ApiBaseRequestBean request = ApiBaseRequestBean.builder()
                .custNo(env.getProperty("qugongbao.custNo"))
                .timestamp(DatePattern.NORM_DATETIME_FORMAT.format(new Date()))
                .reqNo(IdUtils.simpleUUID())
                .body(JSONObject.toJSONString(req))
                .build();
        String signValue = Signer.sign(request, env.getProperty("qugongbao.privateKey"));
        request.setSignValue(signValue);
        String url = env.getProperty("qugongbao.host") + env.getProperty("qugongbao.withdrawalUrl"); //提现
        log.info("request url=" + url);
        log.info("request data=" + JSON.toJSONString(request));
        ResponseEntity<String> temp = restTemplateUtil.post(url, request, String.class);
        if (temp.getStatusCode().value() == HttpStatus.OK.value()) {
            resultMap = JSON.parseObject(temp.getBody(), new TypeReference<Map<String, String>>() {});
        } else {
            throw new RuntimeException("提现申请失败");
        }
        return resultMap;
    }

    //趣工宝提现状态查询接口
    public Map<String, String> withdrawalResultQuery(String custTransId) throws Exception {
        WithdrawalStatusQuery req = WithdrawalStatusQuery.builder()
                .custTransId(custTransId)
                .build();
        ApiBaseRequestBean request = ApiBaseRequestBean.builder()
                .custNo(env.getProperty("qugongbao.custNo"))
                .timestamp(DatePattern.NORM_DATETIME_FORMAT.format(new Date()))
                .reqNo(IdUtil.fastSimpleUUID())
                .body(JSONObject.toJSONString(req))
                .build();
        String signValue = Signer.sign(request, env.getProperty("qugongbao.privateKey"));
        request.setSignValue(signValue);
        String url = env.getProperty("qugongbao.host") + env.getProperty("qugongbao.statusQuery"); //提现状态查询
        log.info("request url=" + url);
        log.info("request data=" + JSON.toJSONString(request));
        ResponseEntity<String> temp = restTemplateUtil.post(url, request, String.class);
        if (temp.getStatusCode().value() == HttpStatus.OK.value()) {
            System.out.println(temp.getStatusCode() + "------" + temp.getBody());
            String response = temp.getBody();
            Map<String, String> resultMap = JSON.parseObject(response, new TypeReference<Map<String, String>>() {});
            if (StrUtil.isNotBlank(resultMap.get(Signer.SIGN_VALUE))) {
                boolean isVerify = Signer.verify(resultMap, env.getProperty("qugongbao.publicKey"));
                if (isVerify) {
                    return resultMap;
                } else {
                    throw new RuntimeException("查询趣工宝支付结果验签失败");
                }
            } else {
                throw new RuntimeException("查询趣工宝支付结果验签失败");
            }
        } else {
            throw new RuntimeException("查询趣工宝支付结果失败");
        }
    }

    //趣工宝提现退票状态查询接口
    public Map<String, String> withdrawalResultForRefund(String orderNo, String refundDate) throws Exception {
        WithdrawalRefundStatusQuery req = WithdrawalRefundStatusQuery.builder()
                .orderNo(orderNo)
                .refundDate(refundDate)
                .build();
        ApiBaseRequestBean request = ApiBaseRequestBean.builder()
                .custNo(env.getProperty("qugongbao.custNo"))
                .timestamp(DatePattern.NORM_DATETIME_FORMAT.format(new Date()))
                .reqNo(IdUtil.fastSimpleUUID())
                .body(JSONObject.toJSONString(req))
                .build();
        String signValue = Signer.sign(request, env.getProperty("qugongbao.privateKey"));
        request.setSignValue(signValue);
        String url = env.getProperty("qugongbao.host") + env.getProperty("qugongbao.queryTaskSettleRefund"); //提现状态查询
        log.info("request url=" + url);
        log.info("request data=" + JSON.toJSONString(request));
        ResponseEntity<String> temp = restTemplateUtil.post(url, request, String.class);
        if (temp.getStatusCode().value() == HttpStatus.OK.value()) {
            System.out.println(temp.getStatusCode() + "------" + temp.getBody());
            String response = temp.getBody();
            Map<String, String> resultMap = JSON.parseObject(response, new TypeReference<Map<String, String>>() {});
            if (StrUtil.isNotBlank(resultMap.get(Signer.SIGN_VALUE))) {
                boolean isVerify = Signer.verify(resultMap, env.getProperty("qugongbao.publicKey"));
                if (isVerify) {
                    return resultMap;
                } else {
                    throw new RuntimeException("查询趣工宝提现退票状态验签失败");
                }
            } else {
                throw new RuntimeException("查询趣工宝提现退票状态验签失败");
            }
        } else {
            throw new RuntimeException("查询趣工宝提现退票状态结果失败");
        }
    }
}
